import './index.scss';
import React, { useEffect, useState, useRef } from "react";
import { user_export_privkey, send_verify_code } from '@/utils/mixin.ts'
import { Button, Form, Input, message, Spin, Modal } from 'antd';
import { ArrowLeftOutlined, CopyOutlined, PlusCircleFilled } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import Logo from '@/assets/photos/LogoLogin.png';
import txtLogin from '@/assets/photos/txtLogin.png';
import { useTranslation } from 'react-i18next';
import  copyIcon from '@/assets/new/copy1.png'

const WalletsDetail = () => {
    const { t } = useTranslation();
    const navigate = useNavigate()
    const [spinning, setSpinning] = React.useState(false);
    const [password, setPassword] = useState('');
    const [tokenAddress, setTokenAddress] = useState('');
    const [btnState, setBtnState] = useState('');
    const [isSending, setIsSending] = useState(false); // 控制按钮是否处于发送中状态
    const [countdown, setCountdown] = useState(60); // 倒计时秒数
    const text = JSON.parse(localStorage.getItem('detail')).address;
    const name = JSON.parse(localStorage.getItem('detail')).name;
    const [code, setCode] = useState('');
    const [username, setUsername] = useState('');
    const [isModalOpen, setIsModalOpen] = useState(false);
    // 获取输入密码
    const handlePasswordChange = (e) => {
        setPassword(e.target.value);
    };

    // 取消返回上一页
    const goBack = () => {
        window.history.go(-1);
    }

    // 返回钱包首页
    const goEthBot= () => {
        navigate('/dashboard/ethbot');
    }
    useEffect(() => {
        if(localStorage.getItem('info')) return
        setIsModalOpen(true)
      }, []);
    // 
    const send = async () => {
        setSpinning(true);
        try {
            const res = await send_verify_code({ email: localStorage.getItem('email') });
            setSpinning(false);
            if(res.code == -1) {
                return message.error(res.msg);
            }
            // 设置按钮状态
            setIsSending(true); 
            // 开始倒计时
            const timer = setInterval(() => {
                setCountdown((prevCountdown) => {
                if (prevCountdown === 1) {
                    clearInterval(timer);
                    setIsSending(false); // 倒计时结束后恢复按钮状态
                    return 60; // 重置倒计时
                }
                return prevCountdown - 1;
                });
            }, 1000);
        } catch (error) {
            setIsSending(false);
            console.error("Error fetching data:", error);
        }
    };

    // 提交密码
    const confrimPassword = async () => {
        if(!code) return message.error(t('Please enter the email verification code'))
        if(!password) return message.error(t('Please enter the password'))
        setSpinning(true);
        user_export_privkey({
            email: localStorage.getItem('email'),
            wallet_id: localStorage.getItem('wallet_id'),
            password: password,
            code

        }).then(res => {
            setSpinning(false);
            if (res && res.code === 0) {
                setBtnState('ok');
                setPassword(res.data.priv_key);
                setTokenAddress(res.data.address);
                // message.success(res.msg);
            } else {
                message.error(res.msg);
            }
        });
    }

    // 复制
    const copyToClipboard = (text) => {
        const tempInput = document.createElement('input');
        tempInput.value = text;
        document.body.appendChild(tempInput);
        tempInput.select();
        tempInput.setSelectionRange(0, 99999);
        document.execCommand('copy');
        document.body.removeChild(tempInput);
        message.success(t('Replicating Success'));
      };

      const handleCodeChange = (e) => {
        setCode(e.target.value);
      };

      const handleUsernameChange = (e) => {
        setUsername(e.target.value);
      };

      const handleOk = () => {
        setIsModalOpen(false);
        localStorage.setItem('info', 'info')
      };

      


    return (
        <div className="walletPassword">
            {console.log('123')}
            <Modal open={isModalOpen} centered onOk={handleOk} className='model_info' okText={t('Understood')}>
                <h4>（{t('Account Security Tips')}）</h4>
                <h4>{t('Protecting Your Funds')}</h4>
                <p>·{t('Your account private key mnemonic controls all your accounts')}.</p>
                <p>·{t('Do not share your account private key mnemonic with anyone')}.</p>
                <p>·{t("The TuringBot team will never ask for your account's private key mnemonic")}.</p>
            </Modal>
            <Spin spinning={spinning} fullscreen />
            <div className="header">
                <Button type="text" onClick={() => window.history.go(-1)} icon={<ArrowLeftOutlined style={{ fontSize: '26px' }} />}></Button>
            </div>
            <div className="content">
                <div className="logo">
                    <div className="img">
                        <img src={Logo} />
                        <img src={txtLogin} />
                    </div>
                    <div className="name">
                        <p>{name}</p>
                        <span>{text}</span>
                    </div>
                    <div className="copyBtn">
                        <Button type="text" className="copyBtn" onClick={() => copyToClipboard(tokenAddress)} icon={<CopyOutlined />}></Button>
                    </div>
                </div>
                <div className="passwordInput">
                    <Form>
                   {!btnState && <div className='send-div'>
                        <Form.Item
                        label=""
                        name="code"
                        className='user'
                        rules={[{ required: true, message: t('Please enter the email verification code') }]}
                        >
                        <Input placeholder={t('Enter email verification code')} value={code} onChange={handleCodeChange}  />
                        </Form.Item>

                        <Button value={username} onClick={() => {send()}} disabled={isSending}>
                            {isSending ? `${countdown}s` : t('send')}
                            </Button>
                        </div>}
                        
                        <Form.Item
                            label=""
                        >
                           {!btnState ? <Input placeholder={t('Please enter the wallet password')} type='password' value={password} onChange={handlePasswordChange} /> : 
                           <div className="copy">
                            <p>{password}</p>
                            <img src={copyIcon} onClick={() => {copyToClipboard(password)}} />
                            </div>}
                        </Form.Item>
                    </Form>
                </div>
                <div className="illustrate">
                    <PlusCircleFilled />
                    {/* <span>Warning: Do not disclose this keyAnyone with your private key canstealany assets held in your account.</span> */}
                    <span>{t('Warning: Do not disclose this key. Anyone using your private key can steal any assets from your account')}</span>
                </div>
                <div className="button">
                    {
                        btnState == 'ok' ? 
                        <div className="okBtn"><Button onClick={() => goEthBot()}>{t('complete')}</Button></div> :
                        <div className="optionBtn">
                            <Button onClick={() => goBack()}>{t('Cancel')}</Button>
                            <Button type="primary" onClick={() => confrimPassword()}>{t('Confirm')}</Button>
                        </div>
                    }

                </div>
            </div>
        </div>
    )

}

export default WalletsDetail;